package com.example.demo.controller;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.naming.java.javaURLContextFactory;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import com.example.demo.dao.JpaBlog;
import com.example.demo.entity.Blog;
@Controller
public class BlogController {
//hihi
	@Autowired
	
	private JpaBlog JpaBlog;
	
	
	@GetMapping("/newBlogPage")
	public String page(){
		return "newblog";
	}
	@PostMapping("/saveBlog")
	public void save(HttpServletRequest request, HttpServletResponse response) throws IOException{
		String title = request.getParameter("title");
		String content = request.getParameter("content");
		Blog blog = new Blog();
		blog.setTitle(title);
		blog.setContent(content);
		
		blog.setCreatTime(LocalDateTime.now());
		blog.setBrowseNum(0);
		if(content.length()>30){
			blog.setShortContent(content.substring(0,30));
		}
		else{
			blog.setShortContent(content);
		}
		
		
		
		JpaBlog.save(blog);
		
		response.sendRedirect("/general");
		
	}
	@Autowired
	private EntityManager entityManager;
	@GetMapping("/general")
	public ModelAndView gen(){
//		
		List<Blog> blogs = JpaBlog.findAll();
		ModelAndView modelAndView = new ModelAndView("general");
		modelAndView.addObject("blogs",blogs);
		return modelAndView ;
		
	}
	
}
